package com.qq.xrx1002.androidgame;

import android.view.MotionEvent;

import org.cocos2d.actions.CCScheduler;
import org.cocos2d.actions.base.CCRepeatForever;
import org.cocos2d.actions.instant.CCCallFunc;
import org.cocos2d.actions.interval.CCAnimate;
import org.cocos2d.actions.interval.CCDelayTime;
import org.cocos2d.actions.interval.CCMoveBy;
import org.cocos2d.actions.interval.CCMoveTo;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.layers.CCTMXObjectGroup;
import org.cocos2d.layers.CCTMXTiledMap;
import org.cocos2d.nodes.CCAnimation;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCLabel;
import org.cocos2d.nodes.CCNode;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.nodes.CCSpriteFrame;
import org.cocos2d.transitions.CCFlipXTransition;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGRect;
import org.cocos2d.types.CGSize;
import org.cocos2d.types.ccColor3B;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Random;

/**
 * Created by Alyson on 2018/11/7.
 */

class CombatLayer extends CCLayer {

    private CGSize winSize;
    private CCSprite ccSprite_SeedBank;
    private CCLabel ccLabel;
    private CCSprite ccSprite_SeedChooser;
    private ArrayList<PlantCard> plantCards;
    private ArrayList<PlantCard> selectPlantCards;
    private boolean isMove;
    private CCSprite ccSprite_SeedChooser_Button;
    private CCTMXTiledMap cctmxTiledMap;
    private ArrayList<CCSprite> ccSprite_show;
    private CCSprite ccSprite_startReady;
    private boolean isStart;
    private PlantCard selectCard;
    private Plant selectPlant;
    private ArrayList<ArrayList<CGPoint>> cgPoint_towers;
    private ArrayList<CombatLine> combatLines;
    private ArrayList<CGPoint> cgPoints_path;
    private Random random;
    private int currentSunNumber=50;
    private ArrayList<Sun> suns;

    public CombatLayer() {
        loadMap();
    }

    private void loadMap() {
        cctmxTiledMap=CCTMXTiledMap.tiledMap("combat/map1.tmx");//CCTMXTiledMap：cocos2d的相对格式的图块地图
        addChild(cctmxTiledMap);//地图加入到图层
        //添加一个对象图层并且名字为show
        CCTMXObjectGroup objectGroup_show=cctmxTiledMap.objectGroupNamed("show");
        ArrayList<HashMap<String, String>> objects=objectGroup_show.objects;//使用数组列表获得所有对象
        ccSprite_show=new ArrayList<>();
        for (HashMap<String, String> object:objects){
            float x=Float.parseFloat(object.get("x"));//强制转换为单精度
            float y=Float.parseFloat(object.get("y"));
            CCSprite ccSprite_shake=CCSprite.sprite("zombies/zombies_1/shake/Frame00.png");
            ccSprite_shake.setPosition(x,y);//获得单精度的位置
            cctmxTiledMap.addChild(ccSprite_shake);//把僵尸的对象添加到地图图层
            ccSprite_show.add(ccSprite_shake);
            ArrayList<CCSpriteFrame> frames=new ArrayList<>();//使用数组列表的方式获取僵尸的动态
            for (int i = 0; i <2 ; i++) {//总共2张图片
                CCSpriteFrame ccSpriteFrame=CCSprite.sprite(String.format(Locale.CHINA,//Locale.CHINA：使用的语言为中文
                        "zombies/zombies_1/shake/Frame%02d.png",i)).displayedFrame();//2位的帧序列的使用
                frames.add(ccSpriteFrame);
            }
            CCAnimation ccAnimation=CCAnimation.animationWithFrames(frames,0.2f);//CCAnimation：帧动画；frames,0.2f：0.2秒执行一帧
            CCAnimate ccAnimate=CCAnimate.action(ccAnimation,true);//帧动画是否重复，true表示重复。
            CCRepeatForever ccRepeatForever=CCRepeatForever.action(ccAnimate);
            ccSprite_shake.runAction(ccRepeatForever);
        }
        winSize= CCDirector.sharedDirector().winSize();
        CCDelayTime ccDelayTime=CCDelayTime.action(2);//延时
        CCMoveBy ccMoveBy=CCMoveBy.action(2,
                ccp(winSize.getWidth()-cctmxTiledMap.getContentSize().getWidth(),0));//移动的距离是手机屏幕的宽度-地图的宽度
        CCCallFunc ccCallFunc=CCCallFunc.action(this,"loadChoose");
        CCSequence ccSequence=CCSequence.actions(ccDelayTime,ccMoveBy,ccCallFunc);//使用串联的方式把延时和移动运行起来
        cctmxTiledMap.runAction(ccSequence);//把串联添加到地图并执行起来
    }

    public void loadChoose(){
        ccSprite_SeedBank=CCSprite.sprite("choose/SeedBank.png");
        ccSprite_SeedBank.setAnchorPoint(0,1);//设置锚点为(0，1)
        ccSprite_SeedBank.setPosition(0,winSize.getHeight());//设置位置：屏幕的左上角
        addChild(ccSprite_SeedBank);//加入图层

        ccLabel=CCLabel.makeLabel("50","",20);//"50":表示大小；"":表示字体；20:表示字体大小
        ccLabel.setColor(ccColor3B.ccBLACK);//设置颜色，默认为白色，所有看不到，则设置为黑色
        ccLabel.setPosition(40,695);
        addChild(ccLabel);//加入图层

        ccSprite_SeedChooser=CCSprite.sprite("choose/SeedChooser.png");
        ccSprite_SeedChooser.setAnchorPoint(0,0);
        addChild(ccSprite_SeedChooser);

        CCSprite ccSprite_SeedChooser_Button_Disabled=CCSprite.
                sprite("choose/SeedChooser_Button_Disabled.png");//添加精灵
        ccSprite_SeedChooser_Button_Disabled.
                setPosition(ccSprite_SeedChooser.getContentSize().getWidth()/2,80);//设置位置在容器里，偏下方
        ccSprite_SeedChooser.addChild(ccSprite_SeedChooser_Button_Disabled);//把按钮放在选择框里

        ccSprite_SeedChooser_Button=CCSprite.sprite("choose/SeedChooser_Button.png");
        ccSprite_SeedChooser_Button.
                setPosition(ccSprite_SeedChooser.getContentSize().getWidth()/2,80);
        ccSprite_SeedChooser.addChild(ccSprite_SeedChooser_Button);
        ccSprite_SeedChooser_Button.setVisible(false);

        plantCards=new ArrayList<>();//用数组列表来存入植物卡片
        selectPlantCards=new ArrayList<>();//存放选中的植物卡片
        for (int i = 0; i <8 ; i++) {
            PlantCard plantCard=new PlantCard(i);
            plantCards.add(plantCard);//植物卡片增加到数组列表里
            plantCard.getDark().setPosition(50+60*i,590);//显示卡片，并且确定位置
            ccSprite_SeedChooser.addChild(plantCard.getDark());//在选择框里加入一个亮精灵
            plantCard.getLight().setPosition(50+60*i,590);//显示卡片，并且确定位置
            ccSprite_SeedChooser.addChild(plantCard.getLight());//在选择框里加入一个暗精灵
        }
        setIsTouchEnabled(true);//设置是否可触摸为真：每个图层需要就得开启，而且有且只有1个图层可触摸
    }
    @Override
    public boolean ccTouchesBegan(MotionEvent event) {//设置触摸
        CGPoint cgPoint=convertTouchToNodeSpace(event);//把原本的Android的数据转换为Cocos2d类型的
        if (isStart){
            if (CGRect.containsPoint(ccSprite_SeedBank.getBoundingBox(),cgPoint)){//判断卡片在待选框里
                if (selectCard!=null){
                    selectCard.getLight().setOpacity(255);
                    selectCard=null;
                }
                    for (PlantCard plantCard:selectPlantCards){
                        if (CGRect.containsPoint(plantCard.getLight().getBoundingBox(),cgPoint)){
                            selectCard=plantCard;//选中的卡片等于植物卡片
                            selectCard.getLight().setOpacity(100);//设置亮精灵的透明的。标志位已选
                            switch (selectCard.getId()){
                                case 0:
                                    selectPlant=new Peashooter();
                                    break;
                                case 1:
                                    selectPlant=new SunFlower();
                                    break;
                                case 2:
                                    selectPlant=new CherryBomb();
                                    break;
                                case 3:
                                    selectPlant=new WallNut();
                                    break;
                                case 4:
                                    selectPlant=new PotatoMine();
                                    break;
                                case 5:
                                    selectPlant=new SnowPea();
                                    break;
                                case 6:
                                    selectPlant=new Chomper();
                                    break;
                                case 7:
                                    selectPlant=new Repeater();
                                    break;
                            }
                        }
                    }
                }else if (selectPlant!=null && selectCard!=null){//取消点击(如果选中的卡片不为空)
                    int col=(int)(cgPoint.x-220)/105;//计算列，就得得到x里面的坐标
                    int row=(int)(cgPoint.y-40)/120;
                    if (col>=0 && col<9 && row>=0 && row<5){
                        CombatLine combatLine=combatLines.get(row);
                        if (!combatLine.isContainPlant(col)){
                            combatLine.addPlant(col,selectPlant);
                            selectPlant.setPosition(cgPoint_towers.get(row).get(col));
                            cctmxTiledMap.addChild(selectPlant);
                            addSunNumber(-selectPlant.getPrice());
                            selectPlant=null;
                            selectCard=null;
                        }
                    }
                }
                else {
                    for (Sun sun:suns){
                        if (CGRect.containsPoint(sun.getBoundingBox(),cgPoint)){
                            sun.collect();
                        }
                    }
            }
        }else {
            if (CGRect.containsPoint(ccSprite_SeedChooser.getBoundingBox(), cgPoint)) {//判断卡片在待选框里
                if (selectPlantCards.size() < 6) {
                    for (PlantCard plantCard : plantCards) {
                        if (CGRect.containsPoint(plantCard.getLight().getBoundingBox(), cgPoint)) {//判断卡片在待选框里
                            if (!selectPlantCards.contains(plantCard)) {//如果选择中的卡片已经包含了
                                selectPlantCards.add(plantCard);//不包含的则需要加进来
                                CCMoveTo ccMoveTo = CCMoveTo.action(0.1f,
                                        ccp(50 + 60 * selectPlantCards.size(), 725));//确定移动到的位置
                                plantCard.getLight().runAction(ccMoveTo);
                                if (selectPlantCards.size() == 6) {//如果选中的卡片等于6。
                                    ccSprite_SeedChooser_Button.setVisible(true);//则把刚刚选中的按钮就设置显示为真
                                }
                            }
                        }
                    }
                }
            }
            if (CGRect.containsPoint(ccSprite_SeedBank.getBoundingBox(), cgPoint)) {//判断卡片在待选框里
                isMove = false;//是否移除(false表示没有移除)
                for (PlantCard plantCard : selectPlantCards) {
                    if (CGRect.containsPoint(plantCard.getLight().getBoundingBox(), cgPoint)) {
                        CCMoveTo ccMoveTo = CCMoveTo.action(0.1f,
                                plantCard.getDark().getPosition());//确定移动到的位置
                        plantCard.getLight().runAction(ccMoveTo);
                        selectPlantCards.remove(plantCard);//不包含的则需要加进来
                        ccSprite_SeedChooser_Button.setVisible(false);
                        isMove = true;
                        break;
                    }
                }
            }
            if (isMove) {//一旦移除，则需要重新来过
                for (int i = 0; i < selectPlantCards.size(); i++) {
                    PlantCard plantCard = selectPlantCards.get(i);
                    CCMoveTo ccMoveTo = CCMoveTo.action(0.1f, ccp(110 + 60 * i, 725));
                    plantCard.getLight().runAction(ccMoveTo);
                }
            }
            if (ccSprite_SeedChooser_Button.getVisible()) {
                if (CGRect.containsPoint(ccSprite_SeedChooser_Button.getBoundingBox(), cgPoint)) {
                    for (PlantCard plantCard : selectPlantCards) {//把选中的植物卡片全找出来
                        addChild(plantCard.getLight());//把亮精灵加到了图层
                    }
                    ccSprite_SeedChooser.removeSelf();//点击选中的按钮则在待选栏移除自身
                    CCMoveTo ccMoveTo = CCMoveTo.action(2, ccp(-100, 0));//把地图移动到居中；移动到负100
                    CCCallFunc ccCallFunc = CCCallFunc.action(this, "startReady");//开始前的准备
                    CCSequence ccSequence = CCSequence.actions(ccMoveTo, ccCallFunc);//串联起来
                    cctmxTiledMap.runAction(ccSequence);//运行并调用startReady方法
                }
            }
        }
        return super.ccTouchesBegan(event);
    }
    public void startReady(){
        for (CCSprite ccSprite:ccSprite_show){
            ccSprite.removeSelf();
        }
        setIsTouchEnabled(false);
        ccSprite_startReady=CCSprite.sprite("startready/startReady_00.png");
        ccSprite_startReady.setPosition(winSize.getWidth()/2,winSize.getHeight()/2);
        addChild(ccSprite_startReady);
        ArrayList<CCSpriteFrame> frames=new ArrayList<>();
        for (int i = 0; i <3 ; i++) {
            CCSpriteFrame ccSpriteFrame=CCSprite.sprite(String.format(Locale.CHINA,
                    "startready/startReady_%02d.png",i)).displayedFrame();
            frames.add(ccSpriteFrame);
        }
        CCAnimation ccAnimation=CCAnimation.animationWithFrames(frames,0.2f);
        CCAnimate ccAnimate=CCAnimate.action(ccAnimation,false);
        CCCallFunc ccCallFunc=CCCallFunc.action(this,"start");
        CCSequence ccSequence=CCSequence.actions(ccAnimate,ccCallFunc);
        ccSprite_startReady.runAction(ccSequence);
    }
    public void start(){
        ccSprite_startReady.removeSelf();
        setIsTouchEnabled(true);
        isStart=true;

        cgPoint_towers=new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            ArrayList<CGPoint> cgPoints_tower=new ArrayList<>();
            CCTMXObjectGroup objectGroup_tower=cctmxTiledMap.objectGroupNamed("tower"+i);
            ArrayList<HashMap<String,String>> objects=objectGroup_tower.objects;
            for (HashMap<String ,String> object:objects){
                float x=Float.parseFloat(object.get("x"));
                float y=Float.parseFloat(object.get("y"));
                cgPoints_tower.add(ccp(x,y));
            }
            cgPoint_towers.add(cgPoints_tower);
        }
        combatLines=new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            combatLines.add(new CombatLine());
        }

        cgPoints_path=new ArrayList<>();
        CCTMXObjectGroup objectGroup_path=cctmxTiledMap.objectGroupNamed("path");
        ArrayList<HashMap<String,String>> objects=objectGroup_path.objects;
        for (HashMap<String,String> object:objects){
            float x=Float.parseFloat(object.get("x"));
            float y=Float.parseFloat(object.get("y"));
            cgPoints_path.add(ccp(x,y));
        }
        random=new Random();
        suns=new ArrayList<>();
        update();
        CCDelayTime ccDelayTime1=CCDelayTime.action(20);
        CCCallFunc ccCallFunc1=CCCallFunc.action(this,"startAddZombie1");
        CCDelayTime ccDelayTime2=CCDelayTime.action(40);
        CCCallFunc ccCallFunc2=CCCallFunc.action(this,"startAddZombie2");
        CCDelayTime ccDelayTime3=CCDelayTime.action(60);
        CCCallFunc ccCallFunc3=CCCallFunc.action(this,"startAddZombie3");
        CCSequence ccSequence=CCSequence.actions(ccDelayTime1,ccCallFunc1,ccDelayTime2,ccCallFunc2,
                ccDelayTime3,ccCallFunc3);
        runAction(ccSequence);
    }
    public void startAddZombie1(){
        CCScheduler.sharedScheduler().schedule("addZombie",this,
                20,false);
    }
    public void startAddZombie2(){
        CCScheduler.sharedScheduler().schedule("addZombie",this,
                10,false);
    }
    public void startAddZombie3(){
        CCScheduler.sharedScheduler().schedule("addZombie",this,
                5,false);
    }

    public void addZombie(float t){
        int i=random.nextInt(5);
        Zombie zombie=new Zombie(this,cgPoints_path.get(2*i),
                cgPoints_path.get(2*i+1));
        cctmxTiledMap.addChild(zombie,5-i);
        combatLines.get(i).addZombie(zombie);//把僵尸加入战斗
    }
    public void end(){
        setIsTouchEnabled(false);
        CCScheduler.sharedScheduler().unschedule("addZombie",this);
        for (CCNode ccNode:cctmxTiledMap.getChildren()){
            ccNode.stopAllActions();
            ccNode.unscheduleAllSelectors();
        }
        for (CCNode ccNode:getChildren()){
            ccNode.stopAllActions();
            ccNode.unscheduleAllSelectors();
        }
        CCSprite ccSprite_ZombiesWon=CCSprite.sprite("zombieswon/ZombiesWon.png");
        ccSprite_ZombiesWon.setPosition(winSize.getWidth()/2,winSize.getHeight()/2);
        addChild(ccSprite_ZombiesWon);
        CCDelayTime ccDelayTime=CCDelayTime.action(2);
        CCCallFunc ccCallFunc=CCCallFunc.action(this,"restart");
        CCSequence ccSequence=CCSequence.actions(ccDelayTime,ccCallFunc);
        ccSprite_ZombiesWon.runAction(ccSequence);
    }
    public void restart(){
        CCScene ccScene=CCScene.node();
        ccScene.addChild(new MenuLayer());
        CCFlipXTransition ccFlipXTransition=CCFlipXTransition.
                transition(2,ccScene,1);
        CCDirector.sharedDirector().replaceScene(ccFlipXTransition);
    }

    public void addSunNumber(int sunNumber) {
        currentSunNumber+=sunNumber;
        ccLabel.setString(currentSunNumber+"");
        update();
    }
    private void update() {
        for (PlantCard plantCard:selectPlantCards){
            int price=0;
            switch (plantCard.getId()){
                case 0:
                    price=100;
                    break;
                case 1:
                    price=50;
                    break;
                case 2:
                    price=150;
                    break;
                case 3:
                    price=50;
                    break;
                case 4:
                    price=25;
                    break;
                case 5:
                    price=175;
                    break;
                case 6:
                    price=150;
                    break;
                case 7:
                    price=200;
                    break;
            }
            if (currentSunNumber>=price){
                plantCard.getLight().setOpacity(255);
            }else {
                plantCard.getLight().setOpacity(30);
            }
        }
    }

    public void addSun(Sun sun) {
        suns.add(sun);
    }

    public void removeSun(Sun sun) {
        suns.remove(sun);
    }
}
